package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.Utils.ManagementException
import org.holynite.fieldmanage.ejbs.AdministratorManagement
import org.holynite.fieldmanage.ejbs.AuthorizationManagement
import org.holynite.fieldmanage.entities.Administrator
import org.holynite.fieldmanage.managed.model.LoginFormBean
import org.holynite.fieldmanage.managed.support.LoginSessionBean
import org.holynite.fieldmanage.types.Exceptions
import org.holynite.fieldmanage.utils.LocaleString

import javax.ejb.EJB
import javax.faces.application.FacesMessage
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.RequestScoped
import javax.faces.bean.SessionScoped
import javax.faces.context.FacesContext
import javax.inject.Inject
import javax.servlet.http.HttpSession

/**
 * Created by midnite on 15/1/6.
 */
@ManagedBean
@RequestScoped
class LoginBean implements Serializable {

	@EJB(beanName = "adminControl")
	AdministratorManagement adminMan
	@EJB(beanName = "adminRoleControl")
	AuthorizationManagement roleService
    @ManagedProperty("#{loginFormBean}")
    LoginFormBean loginForm
    @ManagedProperty("#{loginSessionBean}")
    LoginSessionBean loginSession
	@Inject
	LocaleString locale

	LoginBean() {

	}

	String checkLoggedIn() {
		def message = new FacesMessage()
		try {
			def adminAmount = adminMan.checkAvaliableAdministratorAmout()
			println adminAmount
			if (adminAmount.equals(0)) {
				loginSession.loginAdmin = adminMan.checkDefaultLogin(loginForm.workId, loginForm.pass)
			} else {
                loginSession.loginAdmin = adminMan.checkLogin(loginForm.workId, loginForm.pass)
				def logginRole = roleService.fetchRole(loginSession.loginAdmin.correspondRole)
				logginRole = roleService.fillPrivilege(logginRole)
                loginSession.loginAdmin.role = logginRole
			}
			if (loginSession.loginAdmin) {
                loginSession.session.setAttribute("loggedin", true)
			}
            loginForm.workId = ""
            loginForm.pass = ""
			return "index"
		} catch (ManagementException e) {
			message.severity = FacesMessage.SEVERITY_ERROR
			message.summary = (e.exceptionType.equals(Exceptions.LoginFailed)) ? locale.fetch("adminLoginFailed") : locale.fetch("adminLoginError")
			FacesContext.currentInstance.addMessage(null, message)
			return null
		}
	}

	String unlock() {
		def message = new FacesMessage()
		try {
			if (!adminMan.checkPassword(loginSession.loginAdmin, loginForm.pass)) throw new ManagementException(Exceptions.PasswordMismatched)
            loginSession.session.setAttribute("lockdown", false)
			return "index"
		} catch (ManagementException e) {
			message.severity = FacesMessage.SEVERITY_ERROR
			message.summary = (e.exceptionType.equals(Exceptions.PasswordMismatched)) ? locale.fetch("adminUnlockFailed") : locale.fetch("adminLoginError")
			FacesContext.currentInstance.addMessage(null, message)
			return null
		}
	}

}
